/*
 * @Description: 上传
 * @Author: Rfan
 * @Date: 2022-05-03 10:12:22
 * @LastEditTime: 2022-06-07 18:53:49
 */

import { useEffect, useRef, useState } from 'react';
import { Button, message, Modal, Steps } from 'antd';
import classNames from 'classnames/bind';
import type { InputStatus } from 'antd/es/_util/statusUtils';
import { saveTemplateRelation } from '@/api/accession';
import { useBatchManageContext } from '../../../contexts/BatchManageContext';
import UploadPane from './components/UploadPane';
import TemplatePane from './components/TemplatePane';
import RulePane from './components/RulePane';
import type { ICommonDialog } from '@/interfaces/global';
import styles from '../../../styles/uploadCDDialog.module.scss';

const cx = classNames.bind(styles);
const { Step } = Steps;

const stepList = [
  { title: '上传光盘数据包', key: 0 },
  { title: '条目数据映射', key: 1 },
  { title: '原文挂接配置', key: 2 }
];

interface UploadCDDialogProps extends ICommonDialog {}

const UploadCDDialog = (props: UploadCDDialogProps) => {
  const { visible, onClose } = props;
  const { activeBatch } = useBatchManageContext();

  const ruleRef = useRef(null);

  // 当前step
  const [current, setCurrent] = useState(0);
  // 选中的模板
  const [selectTemplate, setSelectTemplate] = useState(null);
  // 模板选择框状态
  const [templateState, setTemplateState] = useState<InputStatus>('');
  // 存储上传成功后返回的完整条目数据
  const [latestRecord, setLatestRecord] = useState({});

  useEffect(() => {
    if (visible) {
      //
    }
  }, [visible]);

  /**
   * @description: 关闭弹窗
   */
  const onCancel = () => {
    if (JSON.stringify(latestRecord) === '{}') {
      onClose();
    } else {
      onClose(latestRecord);
    }
    setCurrent(0);
    setLatestRecord({});
  };

  const saveRules = () => {
    ruleRef.current.save();
  };

  /**
   * @description 步骤条，前进一步
   */
  const next = () => {
    if (current === 0) {
      console.log('active 0 --------', activeBatch);
      if (activeBatch.attOriginal?.status) {
        setCurrent(current + 1);
      } else {
        message.error('请上传光盘数据包');
      }
    } else if (current === 1) {
      if (selectTemplate) {
        saveTemplateRelation({
          batchId: activeBatch.id,
          templateId: selectTemplate
        }).then((res) => {
          console.log('active 1 --------', res.data);
          setCurrent(current + 1);
        });
      } else {
        setTemplateState('error');
        message.error('请选择模板');
      }
    } else {
      setCurrent(current + 1);
    }
  };

  /**
   * @description 步骤条，返回一步
   */
  const prev = () => {
    setCurrent(current - 1);
  };

  return (
    <Modal
      title="导入CD"
      visible={visible}
      className={cx('upload-cd-dialog')}
      width={600}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        current > 0 && (
          <Button key="prev" onClick={() => prev()}>
            上一步
          </Button>
        ),
        current < stepList.length - 1 && (
          <Button
            key="next"
            type="primary"
            onClick={() => {
              next();
            }}
          >
            下一步
          </Button>
        ),
        current === stepList.length - 1 && (
          <Button key="finish" type="primary" onClick={() => saveRules()}>
            完成
          </Button>
        )
      ]}
    >
      <div className={cx('steps-wrap')}>
        <Steps current={current}>
          {stepList.map((item) => (
            <Step key={item.key} title={item.title} />
          ))}
        </Steps>
        <div className="steps-content">
          {current === 0 && <UploadPane />}
          {current === 1 && (
            <TemplatePane
              value={selectTemplate}
              templateState={templateState}
              onChange={setSelectTemplate}
            />
          )}
          {current === 2 && (
            <RulePane
              ref={ruleRef}
              batchId={activeBatch.id}
              atId={activeBatch.archiveTypeId}
              rule={activeBatch.attOriginalRule}
              onClose={onCancel}
            />
          )}
        </div>
      </div>
    </Modal>
  );
};

export default UploadCDDialog;
